import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository, getConnection } from 'typeorm';
import { CategoryEntity } from './category.entity';
import { CommonObjectProps } from '../../types/obj-type';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(CategoryEntity)
    private readonly booksRepository: Repository<CategoryEntity>,
  ) {}

  async addBook(book: CommonObjectProps): Promise<CategoryEntity> {
    return await this.booksRepository.save(book);
  }

  async books(): Promise<CategoryEntity[]> {
    return await this.booksRepository.find();
  }

  // 查单个
  async getBook(id: number): Promise<CategoryEntity> {
    // @ts-ignore
    return await this.booksRepository.findOne({ where: { id } });
  }

  // 更新
  async update(id: number, book: CommonObjectProps) {
    const result = await getConnection()
      .createQueryBuilder()
      .update(CategoryEntity)
      .set(book)
      .where('id=:id', { id })
      .execute();
    return result;
  }

  // 删除
  async delete(id: number) {
    const result = await getConnection()
      .createQueryBuilder()
      .delete()
      .from(CategoryEntity)
      .where('id=:id', { id })
      .execute();
    return result;
  }
}
